var cgd = {
    initQuery:function () {
        $('#cgd_cgdw').combotree({
            loadFilter:function (rows) {
                return convert(rows);
            },
            onSelect:function (record) {
                $('#cgd_cgr').combobox({
                    url:$.webPath() + '/sys/yg/ygXmList?zgjgId=' + record.id,
                    valueField:'id',
                    textField:'xm'
                });
            }
        });
        $('#cgd_dzck').combobox({
            url:$.webPath() + '/organ/ck/ckmcList',
            valueField:'id',
            textField:'mc',
            panelHeight:'200',
            editable:true
        });

        //客户加载
        $("[name='queryCgd.gys']").qyjgzcombobox();
    },
    initDatagrid:function () {
        $("#grid_cgd").datagrid(cgd.dataOptions);
    },
    initBtn:function () {
        $("#btn_cgd_add").click(function () {
            cgd.showWindow({"htType":"cgrk"});
        });
        $("#btn_tpcgd_add").click(function () {
            cgd.showWindow({"htType":"tpcght"});
        });
        $("#btn_cancel_cgd").click(function () {
            var row = $('#grid_cgd').datagrid('getSelected');
            if (row) {
                $.messager.confirm('确认', '是否取消提交此入库单', function (r) {
                    if (r) {
                        var index = $('#grid_cgd').datagrid('getRowIndex', row);
                        var newRow = row;
                        newRow["zt"] = "ybc";
                        newRow["zt_text"] = "已保存";
                        $.post($.webPath() + '/cggl/cgdgl/cgd_cancel', {"cgd.id":row.id}, function (data) {
                            var obj = eval('(' + data + ')');
                            if (obj.statusCode == '200') {
                                $('#grid_cgd').datagrid('updateRow', {"index":index, row:newRow});
                                cgd.setBtnStatus();
                                $.messager.show({title:'提示框', msg:obj.message, timeout:3000, showType:'slide'});
                            }
                            else {
                                $.messager.alert('提示', obj.message, 'info');
                            }
                        });
                    }
                });
            } else {
                $.messager.alert('提示', "请选择要取消的入库单", 'info');
            }
        });
        $("#btn_cgd_mod").click(function () {
            cgd.showWindow({"cgd.id":$('#grid_cgd').datagrid('getSelected').id,
                "htType":$('#grid_cgd').datagrid('getSelected').cglx});
        });
        $("#btn_cgd_del").click(function () {
            var row = $('#grid_cgd').datagrid('getSelected');
            if (row) {
                $.messager.confirm('确认', '是否确认删除此入库单', function (r) {
                    if (r) {
                        var index = $('#grid_cgd').datagrid('getRowIndex', row);
                        $.post($.webPath() + '/cggl/cgdgl/cgd_del', {"cgd.id":row.id}, function (data) {
                            var obj = eval('(' + data + ')');
                            if (obj.statusCode == '200')
                                $('#grid_cgd').datagrid('deleteRow', index);
                            else
                                $.messager.alert('提示', obj.message, 'info');
                        });
                    }
                });
            } else {
                $.messager.alert('提示', "请选择要删除的入库单", 'info');
            }
        });
        $("#btn_cgd_confirm").click(function () {
            var row = $('#grid_cgd').datagrid('getSelected');
            if (row) {

                $.messager.confirm('确认', '是否提交此入库单', function (r) {
                    if (r) {
                        $("#main_index_center").mask();
                        //$("#btn_cgd_confirm").parent().parent().parent().parent().parent().mask();
                        var index = $('#grid_cgd').datagrid('getRowIndex', row);
                        var newRow = row;
                        newRow["zt"] = "ytj";
                        newRow["zt_text"] = "已提交";


                        $.post($.webPath() + '/cggl/cgdgl/cgd_confirm', {"cgd.id":row.id}, function (data) {
                            var obj = eval('(' + data + ')');
                            if (obj.statusCode == '200') {
                                $("#main_index_center").mask('hide');
                                $("#main_index_center").children(".mask").hide();
                                $("#main_index_center").children(".mask-msg").hide();
                                //$("#btn_cgd_confirm").parent().parent().parent().parent().parent().mask('hide');
                                $('#grid_cgd').datagrid('updateRow', {"index":index, row:newRow});
                                $('#grid_cgd').datagrid('reload');
                                cgd.setBtnStatus();
                                $.messager.show({title:'提示框', msg:obj.message, timeout:3000, showType:'slide'});
                            }
                            else {    $('#grid_cgd').datagrid('reload');
                                $("#main_index_center").mask('hide');
                                $("#main_index_center").children(".mask").hide();
                                $("#main_index_center").children(".mask-msg").hide();
//                                $("#btn_cgd_confirm").parent().parent().parent().parent().parent().mask('hide');
                                $.messager.alert('提示', obj.message, 'info');
                            }
                        });
                    }
                });
            } else {
                $.messager.alert('提示', "请选择要的入库单", 'info');
            }
        });
        //查询
        $("#btn_cgd_search").click(function () {
            $('#grid_cgd').datagrid({pageNumber:1, queryParams:cgd.getQuery()});
        });
        //汇津合作库入库信息导入
        $("#btn_cgd_dr").click(function () {
            var win = $.window({
                title: "汇津合作库入库信息导入",
                width: 450,
                height: 240,
                cache: false,
                url: $.webPath() + "/cggl/cgdgl/cgd_upload",
                modal: true,
                buttons: [
                    {
                        text: '确认',
                        handler: function () {
                            $('#cgd_uploadSubject').form('submit', {
                                onSubmit: function () {
                                    $(win).mask();
                                },
                                success: function (data) {
                                    $(win).mask('hide');
                                    var json = $.parseJSON(data);
                                    if (json.statusCode == 200) {
                                        $(win).window('close');
                                        $('#grid_cgd').datagrid({pageNumber:1, queryParams:cgd.getQuery()});
                                        $.messager.show({
                                            title: '提示',
                                            msg: json.message,
                                            timeout: 3000,
                                            showType: 'slide'
                                        });
                                    } else
                                        $.messager.alert('提示', json.message, 'error');
                                }
                            });
                        }
                    }
                ]
            });
        });
    },
    setBtnStatus:function () {
        var row = $("#grid_cgd").datagrid("getSelected");
        if (row && row.id && row.zt == "ybc") {
            $("#btn_cgd_mod,#btn_cgd_del,#btn_cgd_confirm").show();
            $("#btn_cgd_stock").hide();
            $("#btn_cancel_cgd").hide();
        } else if (row && row.id && row.zt == "ytj") {
            $("#btn_cgd_mod,#btn_cgd_del,#btn_cgd_confirm").hide();
            $("#btn_cgd_stock").show();
            $("#btn_cancel_cgd").show();
        } else {
            $("#btn_cgd_mod,#btn_cgd_del,#btn_cgd_confirm,#btn_cgd_stock #btn_cancel_cgd").hide();
        }
    },
    dataOptions:{
        url:$.webPath() + "/cggl/cgdgl/cgdlist?htType=cgrk&sftzd=false",
        pageNumber:1,
        showFooter:true,
        onDblClickCell:function (index, field, value) {
            if (field == "cgdh") {
                $("#btn_cgd_mod:visible").click();
            }
        },
        loadFilter:function (data) {
            $(data.rows).each(function () {
                //this.zt_text = this.zt == 'ysp' ? "已审批" :
                this.zt_text = this.zt == 'ysp' ? "已分配" :
                        this.zt == 'ybc' ? "已保存" :
                        this.zt == 'ytj' ? "已提交" : this.zt == 'yfk' ? "已反馈" : "未知";
                this.cglx_text = this.cglx == "cgrk" ? "采购入库" : this.cglx == "zddh" ? "直达到货" : "统配采购";
            })
            return data;
        },
        rowStyler:function (index, row) {
            if (row.zt == 'yfk') {
                return 'background-color:yellow';
            }
        },
        onLoadSuccess:function () {
            $(this).datagrid('selectRow', 0);
            cgd.setBtnStatus();

            $(".datagrid-htable .datagrid-cell").css('text-align', 'center');
        },
        onClickRow:function () {
            cgd.setBtnStatus();
        },
        onSelect:function (rowIndex, rowData) {
            if (rowData) {
                cgd.setBtnStatus();
            }
        },
        columns:[
            [
                {field:'cgdh', title:'入库单号', align:'center', width:107, formatter:cgdCell},
                {field:'htbm', title:'采购合同号', align:'center', width: 107},
                {field:'cglx_text', title:'采购类型', align:'center', width:61},
                {field:'fhrq', title:'发货日期', align:'center', width:71},
                {field:'czjr', title:'入库日期', align:'center', width:71},
                {field:'gys_jc', title:'供应商名称', align:'center', width:96},
                {field:'cgsl', title:'采购重量', align:'right',
                    formatter:function (value) {
                        var sl = formatSlForHtml(value);
                        return sl;
                    }, width:96},
                {field:'cgje', title:'采购总金额(元)', align:'right',
                    formatter:function (value) {
                        var sl = formatJeForHtml2(value);
                        return sl;
                    }, width:111},
                /* {field:'glfyje', title:'物流费用(元)', align:'right',
                 formatter:function (value) {
                 var sl = formatJeForHtml2(value);
                 return sl;
                 }, width:111},*/
                {field:'dzck_mc', title:'到货仓库', align:'center', width:75},
                {field:'cggs_jc', title:'采购公司', align:'center', width:67},
                {field:'sbgs_jc', title:'申报公司', align:'center', width:63},
//                {field: 'sbbm_qc', title: '申报部门',align: 'center', width: 59},
                {field:'sbr_xm', title:'申报人', hidden:true},
                {field:'createUser_xm', title:'制单人', hidden:true},
                {field:'yrk', title:'入库状态', width:49, align:'center', formatter:function (value) {
                    if (value == "1")
                        return "已入库";
                    else if (value == "0")
                        return "未入库"
                }},
                {field:'zt_text', title:'状态', align:'center', width:46}
            ]
        ]
    },
    showWindow:function (cgddata) {
        var tit = cgddata["cgd.id"] ? "修改入库单" : "添加入库单";
        cgd.win_cgd = $.window({
            title:tit,
            iconCls:'icon-add2',
            width:1024,
            height:500,
            url:$.webPath() + "/cggl/cgdgl/cgdgl_content",
            data:cgddata,
            buttons:[
                {
                    text:'保存',
                    handler:function () {
                        /*   var fksj = $("#cgd_fksj").datebox("getValue");
                         if (!fksj) {
                         $.messager.confirm('确认', '付款时间没有填写，可能会影响赎货价的计算!是否继续新建?', function (r) {
                         if (r) {
                         cgd_add();
                         }
                         });*/
                        //  } else {
                        cgd_add();
                        // }
                    }
                }
            ]
        });
    },
    showStockWindow:function (cgddata) {
        cgd.win_cgd = $.window({
            title:"入库审核",
            iconCls:'icon-add',
            width:1024,
            height:500,
            url:$.webPath() + "/cggl/cgdgl/cgdgl_stock",
            data:cgddata,
            buttons:[
                {
                    text:'保存',
                    handler:cgd_stock
                }
            ]
        });
    },
    win:{
    },
    showDetail:function (id) {
        if ($("#layout_cgd #cgd_id").val() != id) {
            cgd.alwayshowDetail(id);
        }
    },
    alwayshowDetail:function (id) {
        $('#layout_cgd').layout('remove', 'center');
        $('#layout_cgd').layout('add', {
            region:'center',
            split:true,
            href:$.webPath() + '/cggl/cgdgl/cgdgl_detail?cgd.id=' + id
        });
    },
    getQuery:function () {
        return {
            "zt":$("[name='queryCgd.zt']").val(),
            "cglx":$("[name='queryCgd.cglx']").val(),
            "cgdwId":$("#cgd_cgdw").combotree('getValue'),
            "cgr":$("[name='queryCgd.cgr']").val(),
            "fhrqStart":$('#zdsj_start').datebox('getValue'),
            "fhrqEnd":$('#zdsj_end').datebox('getValue'),
            "dzckId":$('#cgd_dzck').combobox('getValue') == null ? null : $('#cgd_dzck').combotree('getValue'),
            "cgdh":$("[name='queryCgd.cgdh']").val(),
            "htbm":$("[name='queryCgd.htbm']").val(),
            "gysid":$("[name='queryCgd.gys']").val(),
            "rkzt":$("[name='queryCgd.rkzt']").val(),
            "zdr":$("#zdr").val(),
            "dlkhcgd":($("#cgd_dlkhcgd").attr("checked")=='checked')
        }
    },
    selectedRowId:null
}

$(function () {
    //查询条件-加载
    cgd.initQuery();
    //按钮-加载
    cgd.initBtn();
    //列表-加载
    cgd.initDatagrid();
})

function cgd_stock() {
    $("#cgd_mx").edatagrid('saveRow');
    $("#cgdglForm").form('submit', {
        url:$.webPath() + "/cggl/cgdgl/cgd_stock",
        onSubmit:function (param) {
            var data = $('#cgd_mx').edatagrid("getData");
            if (!data.rows.length) {
                $('#cgdglForm').tabs('select', "采购明细");
                $.messager.alert("提示", "采购明细需要填写!", "waring");
                return false;
            }
            var arrayPrefix = 'cgd.cgdmxList';
            //物资计划明细
            var paramString = "{";
            //物资计划明细
            for (var i = 0; i < data.rows.length; i++) {
                if (data.rows[i]['cd.id'] == null || data.rows[i]['cd.id'] == '') {
                    $('#cgdglForm').tabs('select', "采购明细");
                    $.messager.alert('提示', '第' + (i + 1) + '行的产地不能为空 !', 'info');
                    return false;
                } else if (data.rows[i].js == 0 || data.rows[i].js == null) {
                    $('#cgdglForm').tabs('select', "采购明细");
                    $.messager.alert('提示', '第' + (i + 1) + '行的件数不能为0 !', 'info');
                    return false;
                }
                {
                    var objectString = $.toJSONStringSubPrefix(data.rows[i], arrayPrefix + "[" + i + "].",
                        [
                            'id',
                            ['wzgg.id', 'gg.id'],
                            'cd.id',
                            'jzfs.id',
                            'hsj',
                            'bhsj',
                            'bz',
                            'ck',
                            'sbsl',
                            'js',
                            'rksl',
                            'rkjs',
                            'rkjz',
                            'kh.khbm'
                        ]);
                    paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
                }
            }
            if (data.rows && data.rows.length > 0)
                paramString = paramString.substring(0, paramString.length - 1);
            paramString += "}";
            $.extend(param, $.parseJSON(paramString));
            return $(this).form('validate');
        },
        success:function (data) {
            var obj = eval('(' + data + ')');
            if (obj.statusCode == '200') {
                $(cgd.win_cgd).window('close');
                $('#grid_cgd').datagrid('reload');
//                $('#layout_cgd').layout('panel', 'center').panel('refresh');
                $.messager.show({title:'提示框', msg:obj.message, timeout:3000, showType:'slide'});
            } else {
                $.messager.alert('提示', obj.message, 'info');
            }
        }
    });
}

function cgd_add() {
    $(cgd.win_cgd).mask();
    $("#cgd_mx").edatagrid('saveRow');
    $("#cgd_fy").edatagrid('saveRow');
    $('#cgdglForm').tabs('select', "入库单");
    $("#cgdglForm").form('submit', {
        url:$.webPath() + "/cggl/cgdgl/cgd_add",
        onSubmit:function (param) {
            var data = $('#cgd_mx').edatagrid("getChecked");
            var fydata = $('#cgd_fy').edatagrid("getData");
            if (data.length == 0) {
                $(cgd.win_cgd).mask('hide');
                $('#cgdglForm').tabs('select', "采购明细");
                $.messager.alert("提示", "请勾选需要开单的明细!", "waring");
                return false;
            }

            for (var i = 0; i < data.length; i++) {
                if (data[i]['cd.id'] == null || data[i]['cd.id'] == '') {
                    $(cgd.win_cgd).mask('hide');
                    $(".mask").hide();
                    $(".mask-msg").hide();
                    $('#cgdglForm').tabs('select', "采购明细");
                    $.messager.alert('提示', '第' + (i + 1) + '行的产地不能为空 !', 'info');
                    return false;
                }
                if (data[i]['jzfs.id'] == null || data[i]['jzfs.id'] == '') {
                    $(cgd.win_cgd).mask('hide');
                    $(".mask").hide();
                    $(".mask-msg").hide();
                    $('#cgdglForm').tabs('select', "采购明细");
                    $.messager.alert('提示', '第' + (i + 1) + '行的记重方式不能为空 !', 'info');
                    return false;
                }
                /* else if (data[i].js == 0 || data[i].js == null) {
                 $(cgd.win_cgd).mask('hide');
                 $(".mask").hide();
                 $(".mask-msg").hide();
                 $('#cgdglForm').tabs('select', "采购明细");
                 $.messager.alert('提示', '第' + (i + 1) + '行的件数不能为0 !', 'info');
                 return false;
                 }*/
            }

            var arrayPrefix = 'cgd.cgdmxList';
            var fyPrefix = 'cgd.cgfyList';
            //物资计划明细
            var paramString = "{";
            $.each(data, function (i, val) {
                var objectString = $.toJSONStringSubPrefix(val, arrayPrefix + "[" + i + "].",
                    [
                        'id',
                        ['wzgg.id', 'gg.id'],
                        'cd.id',
                        'jzfs.id',
                        'hsj',
                        'bhsj',
                        'ck',
                        'bz',
                        'js',
                        'sbsl',
                        'mxh'
                    ]);
                paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
            });

//                {
//                    var objectString = $.toJSONStringSubPrefix(data.rows[i], arrayPrefix + "[" + i + "].",
//                        [
//                            'id',
//                            ['wzgg.id', 'gg.id'],
//                            'cd.id',
//                            'jzfs.id',
//                            'hsj',
//                            'bhsj',
//                            'bz',
//                            'sbsl',
//                            'js'
//                        ]);
//                    paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
//                }
//            }

            //费用物资计划
            for (var i = 0; i < fydata.rows.length; i++) {
                {
                    var objectString = $.toJSONStringPrefix(fydata.rows[i], fyPrefix + "[" + i + "].");
                    paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
                }
            }
            if (data)
                paramString = paramString.substring(0, paramString.length - 1);
            paramString += "}";
            $.extend(param, $.parseJSON(paramString));
            return $(this).form('validate');
        },
        success:function (data) {
            var obj = eval('(' + data + ')');
            if (obj.statusCode == '200') {
                $(cgd.win_cgd).mask('hide');
                $(cgd.win_cgd).window('close');
                $('#grid_cgd').datagrid('reload');
                //$('#layout_cgd').layout('panel', 'center').panel('refresh');
                $.messager.show({title:'提示框', msg:obj.message, timeout:3000, showType:'slide'});
            } else {
                $(cgd.win_cgd).mask('hide');
                $.messager.alert('提示', obj.message, 'info');
            }
        }
    });
}
